package localcache;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.Objects;
import java.util.concurrent.ExecutionException;

/**
 * 对于key是referrence类型的，需要重写它的equals和hashcode方法
 */
public class LocalCacheTest {
    public static void main(String[] args) {
        LocalCacheTest test = new LocalCacheTest();
        test.test();
    }

    private void test() {
        CacheBuilder builder = CacheBuilder.newBuilder();
        LoadingCache<KeyClass,String> cache = builder.build(new CacheLoader<KeyClass,String>() {
            @Override
            public String load(KeyClass key) throws Exception {
                return key.toString();
            }
        });

        String result = null;
        try {
            KeyClass key = new KeyClass("aaa");
            result = cache.get(key);
            System.out.println(result);
            KeyClass key2 = new KeyClass("aaa");
            result = cache.get(key2);
            System.out.println(result);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    class KeyClass{
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public KeyClass(String name) {
            this.name = name;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            KeyClass keyClass = (KeyClass) o;
            return name.equals(keyClass.name);
        }

        @Override
        public int hashCode() {
            return Objects.hash(name);
        }

        @Override
        public String toString() {
            return getClass().getName() + "@" + Integer.toHexString(hashCode());
        }
    }
}
